package com.dc.free.util;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.jfinal.kit.StrKit;

/**
 * map处理工具
 * @author quan
 *
 */
public class MapUtil {
	
	private static String CHARSET = "UTF-8";
	
	private Map<String, Object> map = new HashMap<String, Object>();

	/**
	 * map转url参数字符
	 * @param map 
	 * @param isEncode 是否对参数值编码
	 * @return
	 */
	public static String buildUrlWithQueryString(Map<String, Object> map, boolean isEncode) {
		StringBuilder sb = new StringBuilder();
		
		for (Entry<String, Object> entry : map.entrySet()) {
			if(sb.length()>0) sb.append("&");
			
			String key = entry.getKey();
			String value = entry.getValue().toString();
			if (StrKit.notBlank(value) && isEncode)
				try {value = URLEncoder.encode(value, CHARSET);} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}
			sb.append(key).append("=").append(value);
		}
		return sb.toString();
	}
	
	/**
	 * ap转url参数有序字符
	 * @param map
	 * @param isEncode  是否对参数值编码
	 * @return
	 */
	public static String buildUrlWithQuerySequenceString(Map<String, Object> map, boolean isEncode) {
		TreeMap<String, Object> treeMap = new TreeMap<String, Object>(map);
		return buildUrlWithQueryString(treeMap, isEncode);
	}
	
	public static MapUtil create(String key, String value) {
		MapUtil mu = new MapUtil();
		return mu.put(key, value);
	}
	
	public static MapUtil create() {
		MapUtil mu = new MapUtil();
		return mu;
	}
	
	public MapUtil put(String key, String value) {
		map.put(key, value);
		return this;
	}
	
	@SuppressWarnings("unchecked")
	public <T> T get(String key) {
		return (T) map.get(key);
	}
	
	public String getStr(String name) {
		return (String) map.get(name);
	}
	
	public Integer getInt(String name) {
		Number number = (Number) map.get(name);
		return number == null ? null : number.intValue();
	}
	
	public Long getLong(String name) {
		Number number = (Number) map.get(name);
		return number == null ? null : number.longValue();
	}
	
	public BigInteger getBigInteger(String name) {
		return (BigInteger) map.get(name);
	}
	
	public Double getDouble(String name) {
		return (Double) map.get(name);
	}
	
	public BigDecimal getBigDecimal(String name) {
		return (BigDecimal) map.get(name);
	}
	
	public Boolean getBoolean(String name) {
		return (Boolean) map.get(name);
	}
	
	@SuppressWarnings("rawtypes")
	public List getList(String name) {
		return (List) map.get(name);
	}
	
	@SuppressWarnings("rawtypes")
	public Map getMap(String name) {
		return (Map) map.get(name);
	}
	
	public Map<String, Object> getData() {
		return map;
	}
	
}
